package com.jinshan.oss.service.impl;

import com.jinshan.oss.service.OssService;
import com.jinshan.oss.util.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 获取原始上传文件名
        String filename = file.getOriginalFilename();
        // 获取上传文件的后缀
        String fileSuffix = filename.substring(filename.lastIndexOf("."), filename.length());
        // 给文件一个新的名字的前缀
        String filePreFix = UUID.randomUUID().toString();
        filePreFix = filePreFix.replaceAll("-", "");
        String newFileName = filePreFix + fileSuffix;
        // 获取文件的输入流
        InputStream inputStream = file.getInputStream();
        return ossTemplate.uploadFile(inputStream, newFileName);
    }

    /**
     * 删除一个文件
     * @param fileName
     * @return
     */
    @Override
    public boolean deleteFile(String fileName) {
        return ossTemplate.deleteSingleFile(fileName);
    }

    /**
     * 删除多个文件
     * @param files
     * @return
     */
    @Override
    public boolean batchDeleteFile(String... files) {
        ArrayList<String> fileNames = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (String file : files) {
                fileNames.add(file);
            }
        }
        return ossTemplate.batchDeleteFile(fileNames);
    }
}
